//
//  LHNetWorkManager.m
//  LHAppUpdateManager
//
//  Created by 美食家 on 18/1/2.
//  Copyright © 2018年 不孤独的美食家. All rights reserved.
//

#import "LHNetWorkManager.h"

@implementation LHNetWorkManager
#pragma mark -
#pragma mark - 开始网络请求
+(void)lh_startRequestWithUrl:(NSString*)url andRequestMethod:(NSString*)method andSuccess:(void(^)(NSDictionary * _Nullable data))success andFailure:(void(^)(NSError * _Nullable error))failure{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:method];
    [request setTimeoutInterval:20];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            failure(error);
        }else{
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            if ([resultDict[@"resultCount"] intValue]==1) {
                NSDictionary*dict=resultDict[@"results"][0];
                success(dict);
            }else{
                NSLog(@"获取到的数据=%@",resultDict);
            }
        }
    }];
    [task resume];
}

#pragma mark -
#pragma mark - 取消网络请求
+ (void)lh_cancelRequest{
    [[NSURLSession sharedSession] invalidateAndCancel];
}

@end
